﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UMLTouch.Business.MVC;
using UMLTouch.Core.Entities;
using UMLTouch.DomainRecognition.Factory;
using System.IO;
using System.Reflection;
using UMLTouch.DomainRecognition;
using UMLTouch.Core.UI;

namespace UMLTouch.Business
{
    public class UMLTouchControler : IUMLTouchControler
    {
        
        public Dictionary<String, IDomainRecognition> AvailableDiagrams { get; set; }
        public IUMLTouchModel Model
        {
            get; protected set;
        }

        public UMLTouchControler(IUMLTouchModel model)
        {
            Model = model;
        }

        public void InputStroke(Stroke s,String context)
        {
            Model.IDiagramContext.First(ctx => ctx.Name.Equals(context)).InputStroke(s);
        }

        public void CreateDiagramContext(String diagramType)
        {
            String DefaultName = diagramType;
            Boolean defaultNotOk=true;
            int cpt=1;

            do
            {
                defaultNotOk = Model.IDiagramContext.Any(dc => dc.Name.Equals(DefaultName, StringComparison.InvariantCultureIgnoreCase));
                if (defaultNotOk)
                {
                    DefaultName = diagramType + cpt.ToString();
                    cpt++;
                }
                
            } while (defaultNotOk);

            CreateDiagramContext(diagramType, DefaultName);
          
        }

        public void CreateDiagramContext(String diagramType,String contextName)
        {
            IDomainRecognition rec;

            if(AvailableDiagrams.TryGetValue(diagramType,out rec))
            {
                IDiagramContext ctx = rec.CreateContext(contextName);
                Model.RegisterContext(ctx);

            }
        }

        public void LoadAvailableDiagrams(string path)
        {
            AvailableDiagrams = new Dictionary<string, IDomainRecognition>();

            String[] diagramsDirectory = Directory.GetFiles(path, "*.dll");

            foreach (String s in diagramsDirectory)
            {
                Assembly tmp = System.Reflection.Assembly.LoadFrom(s);
                var types = tmp.GetTypes().Where(t =>
                       t.GetInterfaces().Any(t2 => t2.Equals(typeof(IDomainRecognition)))
                    );
                if (types.Count() > 0)
                {
                    foreach (Type t in types)
                    {
                        IDomainRecognition item = Activator.CreateInstance(t) as IDomainRecognition;
                        String name = t.Name;
                        if (item != null && !name.Equals(String.Empty))
                        {
                            AvailableDiagrams.Add(name, item);
                        }
                    }
                }
            }
        }

        
    }
}
